package com.shyroke.daydayzhuansvc.service.impl;

import com.querydsl.core.QueryResults;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.shyroke.daydayzhuanapi.dto.AdminSearchLogListDto;
import com.shyroke.daydayzhuanapi.entity.AppEntity;
import com.shyroke.daydayzhuanapi.entity.QSearchLogEntity;
import com.shyroke.daydayzhuanapi.entity.SearchLogEntity;
import com.shyroke.daydayzhuanapi.mapper.SearchLogMapper;
import com.shyroke.daydayzhuansvc.util.Page;
import com.shyroke.daydayzhuansvc.util.TabelData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SearchLogService {

    @Autowired
    private JPAQueryFactory factory;
    @Autowired
    private SearchLogMapper searchLogMapper;

    public TabelData<AdminSearchLogListDto> list(Page page) {
        QSearchLogEntity m = QSearchLogEntity.searchLogEntity;
        JPAQuery<SearchLogEntity> query = factory.selectFrom(m);
        QueryResults<SearchLogEntity> queryResults = query
                .offset(PageRequest.of(page.getPage() - 1, page.getLimit()).getOffset()).limit(page.getLimit())
                .orderBy(m.id.desc())
                .fetchResults();

        List<AdminSearchLogListDto> list = queryResults.getResults().stream().map(e -> searchLogMapper.entityToDto(e)).collect(Collectors.toList());
        return new TabelData(list, (int)queryResults.getTotal());
    }
}
